﻿using System;
using System.Web;

namespace SelArom.Net.Sitefinity.HttpModules
{
	/// <summary>
	/// HttpModule to ensure all pages requested are lower case
	/// </summary>
	public class LowerCaseUrlModule : IHttpModule
	{
		protected HttpContext Context
		{
			get { return HttpContext.Current; }
		}

		// In the Init function, register for HttpApplication 
		// events by adding your handlers.
		public void Init(HttpApplication application)
		{
			application.BeginRequest += Application_BeginRequest;
		}

		// Your BeginRequest event handler.
		private void Application_BeginRequest(Object source, EventArgs e)
		{
			// only handle page requests
			if (Telerik.CmsContext.IsCrawlerRequest) return;

			// get requested page
			var url = Context.Request.Path;
			var urlLowered = url.ToLower();

			// exclude non-pages
			if (!urlLowered.EndsWith(".aspx")) return;
			
			// skip searches and admin
			if (urlLowered.EndsWith("search.aspx") || urlLowered.StartsWith("/sitefinity") || url.EndsWith(".template.aspx") || urlLowered.Contains("telerik.web.ui.dialoghandler.aspx")) return;

			// skip edit pages
			if (Context.Request.Url.Query.ToLower().Contains("cmspagemode")) return;

			// if match, url is lowered
			if (string.Equals(url, urlLowered)) return;

			// redirect to lowercase
			Context.Response.Clear();
			Context.Response.Status = "301 Moved Permanently";
			Context.Response.AddHeader("Location", urlLowered);
			Context.Response.End();
		}

		public void Dispose() { }
	}
}